// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Common from "../Common";
import GoodItem from "./GoodItem";
import DuiHuanDialog from "./DuiHuanDialog";
import {bcSub} from "../common/Helpers";

const {ccclass, property} = cc._decorator;

/**
 * 商城页面
 */
@ccclass
export default class Shop extends Common {

    goodItem: cc.Prefab

    @property(cc.Node)
    content: cc.Node

    @property({
        type: cc.Node,
        displayName: '返回首页按钮'
    })
    backBtn: cc.Node

    /**
     * 兑换弹框
     */
    duiHuanDialog: cc.Node

    data = [
        {id: 1, title: '免费树苗', price: 0.00, imageKey: 2},
        {id: 2, title: '普通树苗', price: 10.00, imageKey: 3},
        {id: 3, title: '低级树苗', price: 40.00, imageKey: 4},
        {id: 4, title: '初级树苗', price: 90.00, imageKey: 5},
        {id: 5, title: '中级树苗', price: 160.00, imageKey: 6},
        {id: 5, title: '高级树苗', price: 300.00, imageKey: 7},
        {id: 6, title: '超级树苗', price: 480.00, imageKey: 8},
        {id: 8, title: '钻石树苗', price: 720.00, imageKey: 9},
    ]
    protected watch = {
        shopGoods: async (goods) => {
            const treeAtlas = await this.getTreeAtlas();
            const goodItemPrefab = await this.getGoodItem();
            this.content.removeAllChildren(true)
            const containerWidth = bcSub(this.node.width, 40)
            // const itemWidth = bcDiv(containerWidth, 2)
            goods.forEach(item => {
                if (item._current_status === 1) { // 已升级
                    return;
                }
                const goodItem = cc.instantiate(goodItemPrefab)
                goodItem.getComponent(GoodItem).init({
                    id: item.id,
                    title: item.name,
                    price: item.invest_money,
                    _can_buy: item._can_buy,
                    image: treeAtlas.getSpriteFrame(item.id.toString()),
                    target: this,
                    onBuy: this.onBuy,
                });
                this.content.addChild(goodItem)
            })
        }
    }

    async start() {
        this.initEmitter();
        this.duiHuanDialog = this.node.getChildByName('duihuan')
        this.initShopGoodLists()
    }

    initShopGoodLists() {
        this.http.get('goods/lists').then(async ({data}) => {
            this._data.shopGoods = data;
        }).catch(console.log)
    }

    /**
     * 点击兑换按钮（显示确认框）
     * @param id
     */
    async onBuy(id) {
        this.onBtnClick()
        const item = this.getGoodById(id)
        if (!item) {
            return this.showToast('商品不存在');
        }
        const treeAtlas = await this.getTreeAtlas();
        // @ts-ignore
        const account = this._data.userInfo.account || {}
        this.duiHuanDialog.getComponent(DuiHuanDialog).init({
            id: item.id,
            userAmount: account.cash_account || 0.00,
            title: item.name,
            price: item.invest_money,
            image: treeAtlas.getSpriteFrame(item.id.toString()),
            target: this,
            onConfirm: this.onBuyConfirm,
        })
        this.duiHuanDialog.active = true
    }

    /**
     * 确认购买
     * @param id
     */
    async onBuyConfirm(id) {
        this.onBtnClick()
        try {
            const {message} = await this.http.post('orders/create', {product_id: id})
            this.showToast(message);
            this.duiHuanDialog.active = false
            this.initShopGoodLists();
            await this.initUserInfo(true)
        } catch ({message}) {
            console.log(message)
            this.showToast(message);
        }

    }

    protected getGoodById(id) {
        for (let item of this._data.shopGoods) {
            if (id === item.id) {
                return item
            }
        }
    }

    /**
     * 事件监听
     */
    protected initEmitter() {
        this.backBtn.on(cc.Node.EventType.TOUCH_START, () => {
            this.onBtnClick()
            cc.director.loadScene('profile')
        }, this) // 点击返回首页按钮
    }

    async getGoodItem() {
        if (!this.goodItem) {
            this.goodItem = await this.getPrefab('good')
        }
        return this.goodItem
    }

    // update (dt) {}
}
